import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:multi_camera_plugin/multi_camera_plugin.dart';
import 'package:flutter/foundation.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    // 在应用销毁时释放摄像头资源
    MultiCameraPlugin.instance.dispose();
    print('🔄 应用销毁，已释放所有摄像头资源');
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    switch (state) {
      case AppLifecycleState.resumed:
        print('📱 应用前台');
        break;
      case AppLifecycleState.paused:
        print('📱 应用后台');
        break;
      case AppLifecycleState.detached:
        print('📱 应用分离');
        // 应用被系统杀死前释放资源
        MultiCameraPlugin.instance.dispose();
        break;
      case AppLifecycleState.inactive:
        print('📱 应用非活跃');
        break;
      case AppLifecycleState.hidden:
        print('📱 应用隐藏');
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '多摄像头插件示例',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        useMaterial3: true,
      ),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('多摄像头插件示例'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text(
              '选择初始化方式:',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 30),
            ElevatedButton.icon(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const CameraExamplePage(
                      useAutoInitialization: false,
                    ),
                  ),
                );
              },
              icon: const Icon(Icons.settings),
              label: const Text('手动初始化示例'),
              style: ElevatedButton.styleFrom(
                minimumSize: const Size(200, 50),
              ),
            ),
            const SizedBox(height: 20),
            ElevatedButton.icon(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const CameraExamplePage(
                      useAutoInitialization: true,
                    ),
                  ),
                );
              },
              icon: const Icon(Icons.auto_awesome),
              label: const Text('自动初始化示例'),
              style: ElevatedButton.styleFrom(
                minimumSize: const Size(200, 50),
              ),
            ),
            const SizedBox(height: 40),
            const Padding(
              padding: EdgeInsets.symmetric(horizontal: 20),
              child: Text(
                '手动初始化：需要手动调用initialize方法\n自动初始化：在首次使用摄像头时自动初始化',
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.grey),
              ),
            ),
            const SizedBox(height: 30),
            ElevatedButton.icon(
              onPressed: () async {
                await MultiCameraPlugin.instance.dispose();
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('已释放所有摄像头资源'),
                    backgroundColor: Colors.orange,
                  ),
                );
              },
              icon: const Icon(Icons.cleaning_services),
              label: const Text('释放所有资源'),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.orange,
                foregroundColor: Colors.white,
                minimumSize: const Size(200, 50),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class CameraExamplePage extends StatefulWidget {
  final bool useAutoInitialization;

  const CameraExamplePage({
    super.key,
    this.useAutoInitialization = false,
  });

  @override
  State<CameraExamplePage> createState() => _CameraExamplePageState();
}

class _CameraExamplePageState extends State<CameraExamplePage> {
  final MultiCameraPlugin _plugin = MultiCameraPlugin.instance;

  CameraStatus _status = CameraStatus.uninitialized;
  CameraImplementationType? _currentImplementation;
  List<CameraImplementationType> _availableImplementations = [];
  CameraLensDirection _currentDirection = CameraLensDirection.back;
  FlashMode _currentFlashMode = FlashMode.off;
  String? _lastCapturedImage;
  String _statusMessage = '';
  bool _isCircular = false; // 添加形状切换状态

  late StreamSubscription _statusSubscription;
  late StreamSubscription _errorSubscription;
  late StreamSubscription _eventSubscription;

  @override
  void initState() {
    super.initState();
    _setupListeners();

    // 初始化状态
    setState(() {
      _status = _plugin.status;
      _currentImplementation = _plugin.currentImplementation;
      _availableImplementations = _plugin.availableImplementations;
    });

    // 根据参数决定是否启用自动初始化
    if (widget.useAutoInitialization) {
      _enableAutoInitialization();
    }

    print(
        '🏁 Demo应用初始化完成 (${widget.useAutoInitialization ? "自动初始化" : "手动初始化"})');
    print('📊 初始状态: ${_getStatusName(_status)}');
    print(
        '🔧 可用实现: ${_availableImplementations.map(_getImplementationName).join(', ')}');
  }

  @override
  void dispose() {
    // 取消stream订阅
    _statusSubscription.cancel();
    _errorSubscription.cancel();
    _eventSubscription.cancel();

    // 在自动初始化模式下禁用自动初始化，避免其他页面受影响
    if (widget.useAutoInitialization) {
      _plugin.disableAutoInitialization();
      print('🔄 已禁用自动初始化');
    }

    // 注意：不在这里调用 _plugin.dispose()，因为插件是单例
    // 只有在应用真正退出时才应该释放所有资源
    print(
        '📱 CameraExamplePage 已释放 (${widget.useAutoInitialization ? "自动初始化" : "手动初始化"})');
    super.dispose();
  }

  /// 设置监听器
  void _setupListeners() {
    _statusSubscription = _plugin.statusStream.listen((status) {
      print('📱 状态变化: ${_getStatusName(status)}');
      if (mounted) {
        setState(() {
          _status = status;
          _currentImplementation = _plugin.currentImplementation;
          _availableImplementations = _plugin.availableImplementations;
        });
      }
    });

    _errorSubscription = _plugin.errorStream.listen((error) {
      print('❌ 摄像头错误: ${error.message}');
      if (mounted) {
        setState(() {
          _statusMessage = '错误: ${error.message}';
        });
        _showSnackBar('摄像头错误: ${error.message}', isError: true);
      }
    });

    _eventSubscription = _plugin.eventStream.listen((event) {
      print('🎬 摄像头事件: ${event.runtimeType}');
      if (mounted) {
        if (event is CameraImplementationSwitchedEvent) {
          setState(() {
            _currentImplementation = event.newImplementation;
            _statusMessage =
                '已切换到: ${_getImplementationName(event.newImplementation)}';
          });
          _showSnackBar(
            '摄像头实现已切换: ${_getImplementationName(event.oldImplementation)} → ${_getImplementationName(event.newImplementation)}\n原因: ${event.reason}',
          );
        } else if (event is CameraCaptureCompletedEvent) {
          setState(() {
            _lastCapturedImage = event.result.imagePath;
            _statusMessage = '拍照成功: ${_formatPath(event.result.imagePath)}';
          });
          _showSnackBar('拍照成功！');
        } else if (event is AutoInitializationStartedEvent) {
          setState(() {
            _statusMessage = '自动初始化开始...';
          });
          _showSnackBar('自动初始化开始...');
        } else if (event is AutoInitializationCompletedEvent) {
          if (event.success) {
            setState(() {
              _status = _plugin.status;
              _currentImplementation = _plugin.currentImplementation;
              _availableImplementations = _plugin.availableImplementations;
              _statusMessage = '自动初始化成功';
            });
            _showSnackBar('自动初始化成功！');
          } else {
            setState(() {
              _statusMessage = '自动初始化失败: ${event.errorMessage ?? "未知错误"}';
            });
            _showSnackBar('自动初始化失败: ${event.errorMessage ?? "未知错误"}',
                isError: true);
          }
        } else if (event is CameraStatusChangedEvent) {
          // 当摄像头状态发生变化时，更新可用实现列表
          setState(() {
            _status = _plugin.status;
            _currentImplementation = _plugin.currentImplementation;
            _availableImplementations = _plugin.availableImplementations;
          });
        }
      }
    });
  }

  /// 启用自动初始化并立即开始初始化
  void _enableAutoInitialization() async {
    setState(() {
      _statusMessage = '正在启用自动初始化...';
    });

    final config = CameraConfig(
      lensDirection: _currentDirection,
      enableAudio: false,
      imageQuality: 0.8,
      isCircular: false,
      isSquare: false,
      enableAutoInitialization: true,
    );

    await _plugin.enableAutoInitialization(config: config, context: context);

    // 立即更新状态
    setState(() {
      _status = _plugin.status;
      _currentImplementation = _plugin.currentImplementation;
      _availableImplementations = _plugin.availableImplementations;
      _statusMessage = '自动初始化已启用，正在初始化摄像头...';
    });

    print(
        '🔄 自动初始化已启用，可用实现: ${_availableImplementations.map(_getImplementationName).join(', ')}');

    // 刷新状态
    _refreshPluginState();
  }

  /// 刷新插件状态
  void _refreshPluginState() {
    if (mounted) {
      final newStatus = _plugin.status;
      final newImplementation = _plugin.currentImplementation;
      final newAvailableImplementations = _plugin.availableImplementations;

      print(
          '🔄 刷新状态: ${_getStatusName(newStatus)}, 实现: ${newImplementation != null ? _getImplementationName(newImplementation) : 'null'}, 可用: ${newAvailableImplementations.length}');

      setState(() {
        _status = newStatus;
        _currentImplementation = newImplementation;
        _availableImplementations = newAvailableImplementations;
      });
    }
  }

  /// 初始化摄像头
  Future<void> _initializeCamera() async {
    try {
      print('🚀 开始初始化摄像头...');
      print('📊 当前状态: ${_getStatusName(_plugin.status)}');

      if (mounted) {
        setState(() {
          _statusMessage = '正在初始化摄像头...';
        });
      }

      final config = CameraConfig(
        lensDirection: _currentDirection,
        enableAudio: false,
        imageQuality: 0.8,
        isCircular: false,
        isSquare: false,
        enableAutoInitialization: false,
      );

      print(
          '⚙️ 使用配置: 方向=${_currentDirection == CameraLensDirection.front ? '前置' : '后置'}');
      await _plugin.initialize(config: config, context: context);

      print('✅ 摄像头初始化完成');
      print('📱 新状态: ${_getStatusName(_plugin.status)}');
      print(
          '💡 当前实现: ${_plugin.currentImplementation != null ? _getImplementationName(_plugin.currentImplementation!) : 'null'}');

      if (mounted) {
        setState(() {
          _statusMessage = '摄像头初始化成功';
        });
      }
    } catch (e) {
      print('❌ 初始化失败: $e');
      if (mounted) {
        setState(() {
          _statusMessage = '初始化失败: $e';
        });
        _showSnackBar('初始化失败: $e', isError: true);
      }
    }
  }

  /// 拍照
  Future<void> _takePicture() async {
    try {
      setState(() {
        _statusMessage = '正在拍照...';
      });

      await _plugin.takePicture();
    } catch (e) {
      setState(() {
        _statusMessage = '拍照失败: $e';
      });
      _showSnackBar('拍照失败: $e', isError: true);
    }
  }

  /// 切换摄像头方向
  Future<void> _switchCamera() async {
    try {
      final newDirection = _currentDirection == CameraLensDirection.back
          ? CameraLensDirection.front
          : CameraLensDirection.back;

      await _plugin.switchCamera(newDirection);

      setState(() {
        _currentDirection = newDirection;
        _statusMessage =
            '已切换到${newDirection == CameraLensDirection.front ? '前置' : '后置'}摄像头';
      });
    } catch (e) {
      _showSnackBar('切换摄像头失败: $e', isError: true);
    }
  }

  /// 切换闪光灯模式
  Future<void> _toggleFlash() async {
    try {
      final modes = [
        FlashMode.off,
        FlashMode.on,
        FlashMode.auto,
        FlashMode.torch
      ];
      final currentIndex = modes.indexOf(_currentFlashMode);
      final newMode = modes[(currentIndex + 1) % modes.length];

      await _plugin.setFlashMode(newMode);

      setState(() {
        _currentFlashMode = newMode;
        _statusMessage = '闪光灯模式: ${_getFlashModeName(newMode)}';
      });
    } catch (e) {
      _showSnackBar('设置闪光灯失败: $e', isError: true);
    }
  }

  /// 手动切换实现方案
  Future<void> _switchImplementation(
      CameraImplementationType implementation) async {
    try {
      print('🔄 UI: 开始切换到 ${_getImplementationName(implementation)}');
      await _plugin.switchImplementation(implementation);
      print('✅ UI: 切换成功');

      // 立即更新UI状态，确保同步
      if (mounted) {
        setState(() {
          _currentImplementation = _plugin.currentImplementation;
          _statusMessage = '已切换到: ${_getImplementationName(implementation)}';
        });
      }

      _showSnackBar('已切换到: ${_getImplementationName(implementation)}');
    } catch (e) {
      print('❌ UI: 切换失败 - $e');
      final errorMessage = '切换实现方案失败: $e';
      _showSnackBar(errorMessage, isError: true);

      // 显示详细错误对话框
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('切换失败'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text('切换摄像头实现方案时发生错误：'),
              const SizedBox(height: 8),
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.red[50],
                  border: Border.all(color: Colors.red[200]!),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Text(
                  e.toString(),
                  style: const TextStyle(
                    fontFamily: 'monospace',
                    fontSize: 12,
                  ),
                ),
              ),
              const SizedBox(height: 8),
              const Text(
                '请检查控制台日志获取更多详细信息。',
                style: TextStyle(fontSize: 12, color: Colors.grey),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('确定'),
            ),
          ],
        ),
      );
    }
  }

  /// 构建摄像头预览
  Widget _buildPreview() {
    final screenSize = MediaQuery.of(context).size;
    final availableWidth = screenSize.width - 100; // 左右各50边距
    final availableHeight = screenSize.height - 300; // 为其他UI元素预留空间

    final double previewSize;
    if (_isCircular) {
      // 圆形：取较小值的80%
      previewSize =
          [availableWidth, availableHeight].reduce((a, b) => a < b ? a : b) *
              0.8;
    } else {
      // 正方形：使用稍大的尺寸
      previewSize =
          [availableWidth, availableHeight].reduce((a, b) => a < b ? a : b) *
              0.9;
    }

    return Center(
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 50), // 左右各50边距
        child: _isCircular
            ? MultiCameraPreview(
                cameraConfig: CameraConfig(
                  lensDirection: _currentDirection,
                  enableAudio: false,
                  imageQuality: 0.8,
                  isCircular: false,
                  isSquare: false,
                  enableAutoInitialization: widget.useAutoInitialization,
                ),
                previewConfig: CameraPreviewConfig.circular(
                  size: previewSize,
                  showBorder: true,
                  borderColor: 0xFF2196F3, // 蓝色边框
                  borderWidth: 3.0,
                ),
                showStatusIndicator: true,
                showImplementationIndicator: true,
                onCameraReady: () {
                  if (mounted) {
                    setState(() {
                      _statusMessage = '摄像头预览已就绪';
                    });
                  }
                },
                onError: (error) {
                  if (mounted) {
                    setState(() {
                      _statusMessage = '预览错误: ${error.message}';
                    });
                  }
                },
                onImplementationSwitched: (old, newImpl, reason) {
                  if (mounted) {
                    setState(() {
                      _statusMessage =
                          '实现已切换: ${_getImplementationName(old)} → ${_getImplementationName(newImpl)}';
                    });
                  }
                },
              )
            : MultiCameraPreview(
                cameraConfig: CameraConfig(
                  lensDirection: _currentDirection,
                  enableAudio: false,
                  imageQuality: 0.8,
                  isCircular: false,
                  isSquare: false,
                  enableAutoInitialization: widget.useAutoInitialization,
                ),
                previewConfig: CameraPreviewConfig.square(
                  size: previewSize,
                  borderRadius: 15.0,
                  showBorder: true,
                  borderColor: 0xFF4CAF50, // 绿色边框
                  borderWidth: 3.0,
                ),
                showStatusIndicator: true,
                showImplementationIndicator: true,
                onCameraReady: () {
                  if (mounted) {
                    setState(() {
                      _statusMessage = '摄像头预览已就绪';
                    });
                  }
                },
                onError: (error) {
                  if (mounted) {
                    setState(() {
                      _statusMessage = '预览错误: ${error.message}';
                    });
                  }
                },
                onImplementationSwitched: (old, newImpl, reason) {
                  if (mounted) {
                    setState(() {
                      _statusMessage =
                          '实现已切换: ${_getImplementationName(old)} → ${_getImplementationName(newImpl)}';
                    });
                  }
                },
              ),
      ),
    );
  }

  /// 构建占位符
  Widget _buildPlaceholder() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          if (_status == CameraStatus.initializing)
            const CircularProgressIndicator(color: Colors.blue),
          const SizedBox(height: 16),
          Text(
            _status == CameraStatus.uninitialized
                ? (widget.useAutoInitialization
                    ? '点击拍照按钮或切换摄像头将自动初始化'
                    : '点击初始化按钮开始')
                : _getStatusName(_status),
            style: const TextStyle(color: Colors.black87, fontSize: 16),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  /// 切换相机形状
  void _toggleCameraShape() {
    setState(() {
      _isCircular = !_isCircular;
      _statusMessage = _isCircular ? '切换到圆形预览' : '切换到正方形预览';
    });
  }

  /// 检查权限状态
  Future<void> _checkPermission() async {
    try {
      // 导入权限管理器
      // import 'package:multi_camera_plugin/multi_camera_plugin.dart';

      final result = await PermissionManager.handleCameraPermission(
        context,
        showDialog: true,
      );

      // 显示权限检查结果
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('权限检查结果'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildPermissionInfo('相机权限', result.hasCameraPermission),
              if (result.hasMicrophonePermission != null)
                _buildPermissionInfo('麦克风权限', result.hasMicrophonePermission!),
              if (result.needsManualSettings)
                const Text(
                  '\n⚠️ 需要手动到系统设置中开启权限',
                  style: TextStyle(
                      color: Colors.orange, fontWeight: FontWeight.bold),
                ),
              if (result.userDenied)
                const Text(
                  '\n❌ 用户拒绝了权限请求',
                  style: TextStyle(color: Colors.red),
                ),
              if (result.hasError && result.errorMessage != null)
                Text(
                  '\n错误: ${result.errorMessage}',
                  style: const TextStyle(color: Colors.red, fontSize: 12),
                ),
            ],
          ),
          actions: [
            if (result.needsManualSettings)
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  openAppSettings();
                },
                child: const Text('去设置'),
              ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('确定'),
            ),
          ],
        ),
      );

      setState(() {
        _statusMessage = result.isGranted ? '权限检查通过' : '权限检查失败';
      });
    } catch (e) {
      _showSnackBar('权限检查失败: $e', isError: true);
    }
  }

  /// 构建权限信息行
  Widget _buildPermissionInfo(String name, bool granted) {
    return Row(
      children: [
        Icon(
          granted ? Icons.check_circle : Icons.cancel,
          color: granted ? Colors.green : Colors.red,
          size: 20,
        ),
        const SizedBox(width: 8),
        Text(
          '$name: ${granted ? '已授权' : '未授权'}',
          style: TextStyle(
            color: granted ? Colors.green : Colors.red,
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }

  /// 处理摄像头操作（拍照或恢复session）
  Future<void> _handleCameraAction() async {
    if (_status == CameraStatus.sessionPaused) {
      // 如果session已暂停，则恢复session
      try {
        await _plugin.resumeSession();
        setState(() {
          _statusMessage = 'Session已恢复，可以拍照了';
        });
      } catch (e) {
        _showSnackBar('恢复session失败: $e', isError: true);
      }
    } else if (_status == CameraStatus.initialized) {
      // 正常拍照
      await _takePicture();
    }
  }

  /// 获取摄像头操作按钮文本
  String _getCameraActionText() {
    if (_status == CameraStatus.sessionPaused) {
      return '恢复拍照';
    }
    return '拍照';
  }

  /// 显示SnackBar
  void _showSnackBar(String message, {bool isError = false}) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: isError ? Colors.red : null,
        duration: const Duration(seconds: 3),
      ),
    );
  }

  /// 格式化文件路径显示，优先显示文件名，前面用省略号
  String _formatPath(String fullPath) {
    const int maxLength = 50; // 最大显示长度

    if (fullPath.length <= maxLength) {
      return fullPath;
    }

    // 跨平台获取文件名，同时处理 / 和 \ 分隔符
    final fileName = fullPath.split(RegExp(r'[/\\]')).last;

    // 如果文件名本身就很长，只显示文件名的后半部分
    if (fileName.length > maxLength - 6) {
      return '......${fileName.substring(fileName.length - (maxLength - 6))}';
    }

    // 计算可以显示的路径前缀长度
    final availableLength = maxLength - fileName.length - 6; // 6是"......"的长度

    if (availableLength <= 0) {
      return '......$fileName';
    }

    // 显示部分路径前缀 + ...... + 文件名
    final pathPrefix = fullPath.substring(0, availableLength);
    return '$pathPrefix......$fileName';
  }

  /// 获取实现方案名称
  String _getImplementationName(CameraImplementationType implementation) {
    switch (implementation) {
      case CameraImplementationType.flutterCamera:
        return 'Flutter Camera';
      case CameraImplementationType.native:
        return '原生实现';
    }
  }

  /// 获取闪光灯模式名称
  String _getFlashModeName(FlashMode mode) {
    switch (mode) {
      case FlashMode.off:
        return '关闭';
      case FlashMode.on:
        return '开启';
      case FlashMode.auto:
        return '自动';
      case FlashMode.torch:
        return '常亮';
    }
  }

  /// 获取状态名称
  String _getStatusName(CameraStatus status) {
    switch (status) {
      case CameraStatus.uninitialized:
        return '未初始化';
      case CameraStatus.initializing:
        return '初始化中';
      case CameraStatus.initialized:
        return '已就绪';
      case CameraStatus.takingPicture:
        return '拍照中';
      case CameraStatus.sessionPaused:
        return 'Session已暂停';
      case CameraStatus.error:
        return '错误';
      case CameraStatus.disposed:
        return '已释放';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white, // 设置白色背景
      appBar: AppBar(
        title: Text(widget.useAutoInitialization ? '自动初始化示例' : '手动初始化示例'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Column(
        children: [
          // 状态信息面板
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(16),
            color: Colors.grey[100],
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('模式: ${widget.useAutoInitialization ? "自动初始化" : "手动初始化"}'),
                Text('状态: ${_getStatusName(_status)}'),
                if (_currentImplementation != null)
                  Text(
                      '当前实现: ${_getImplementationName(_currentImplementation!)}'),
                Text(
                    '摄像头方向: ${_currentDirection == CameraLensDirection.front ? '前置' : '后置'}'),
                Text('闪光灯: ${_getFlashModeName(_currentFlashMode)}'),
                if (_statusMessage.isNotEmpty)
                  Text(
                    '消息: $_statusMessage',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                if (_lastCapturedImage != null)
                  Text(
                    '最后拍照: ${_formatPath(_lastCapturedImage!)}',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
              ],
            ),
          ),

          // 摄像头预览区域
          Expanded(
            child: Container(
              width: double.infinity,
              color: Colors.white,
              child: (_status == CameraStatus.initialized ||
                      _status == CameraStatus.sessionPaused)
                  ? _buildPreview()
                  : _buildPlaceholder(),
            ),
          ),

          // 控制按钮
          Container(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                // 第一行按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 2),
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 2, vertical: 8),
                            minimumSize: const Size(0, 40),
                          ),
                          onPressed: !widget.useAutoInitialization &&
                                  (_status == CameraStatus.uninitialized ||
                                      _status == CameraStatus.error)
                              ? _initializeCamera
                              : null,
                          child: Text(
                            widget.useAutoInitialization ? '自动初始化' : '手动初始化',
                            style: const TextStyle(fontSize: 10),
                            textAlign: TextAlign.center,
                            maxLines: 2,
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 2),
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 2, vertical: 8),
                            minimumSize: const Size(0, 40),
                          ),
                          onPressed: (_status == CameraStatus.initialized ||
                                  _status == CameraStatus.sessionPaused)
                              ? _handleCameraAction
                              : null,
                          child: Text(
                            _getCameraActionText(),
                            style: const TextStyle(fontSize: 10),
                            textAlign: TextAlign.center,
                            maxLines: 2,
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 2),
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 2, vertical: 8),
                            minimumSize: const Size(0, 40),
                          ),
                          onPressed: _status == CameraStatus.initialized
                              ? _switchCamera
                              : null,
                          child: const Text(
                            '切换摄像头',
                            style: TextStyle(fontSize: 10),
                            textAlign: TextAlign.center,
                            maxLines: 2,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),

                // 第二行按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 2),
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 2, vertical: 8),
                            minimumSize: const Size(0, 40),
                          ),
                          onPressed: _status == CameraStatus.initialized
                              ? _toggleFlash
                              : null,
                          child: const Text(
                            '切换闪光灯',
                            style: TextStyle(fontSize: 10),
                            textAlign: TextAlign.center,
                            maxLines: 2,
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 2),
                        child: ElevatedButton(
                          onPressed: _status == CameraStatus.initialized
                              ? _toggleCameraShape
                              : null,
                          style: ElevatedButton.styleFrom(
                            backgroundColor:
                                _isCircular ? Colors.blue : Colors.green,
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(
                                horizontal: 2, vertical: 8),
                            minimumSize: const Size(0, 40),
                          ),
                          child: Text(
                            _isCircular ? '圆形' : '正方形',
                            style: const TextStyle(fontSize: 10),
                            textAlign: TextAlign.center,
                            maxLines: 2,
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 2),
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 2, vertical: 8),
                            minimumSize: const Size(0, 40),
                          ),
                          onPressed: () => _showImplementationDialog(),
                          child: const Text(
                            '切换实现',
                            style: TextStyle(fontSize: 10),
                            textAlign: TextAlign.center,
                            maxLines: 2,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),

                // 第三行按钮（权限检查和session控制）
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 2),
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.orange,
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(
                                horizontal: 2, vertical: 8),
                            minimumSize: const Size(0, 40),
                          ),
                          onPressed: _checkPermission,
                          child: const Text(
                            '检查权限',
                            style: TextStyle(fontSize: 10),
                            textAlign: TextAlign.center,
                            maxLines: 2,
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 2),
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor:
                                _status == CameraStatus.sessionPaused
                                    ? Colors.green
                                    : Colors.red,
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(
                                horizontal: 2, vertical: 8),
                            minimumSize: const Size(0, 40),
                          ),
                          onPressed: _status == CameraStatus.initialized
                              ? () async {
                                  try {
                                    await _plugin.pauseSession();
                                  } catch (e) {
                                    _showSnackBar('暂停session失败: $e',
                                        isError: true);
                                  }
                                }
                              : _status == CameraStatus.sessionPaused
                                  ? () async {
                                      try {
                                        await _plugin.resumeSession();
                                      } catch (e) {
                                        _showSnackBar('恢复session失败: $e',
                                            isError: true);
                                      }
                                    }
                                  : null,
                          child: Text(
                            _status == CameraStatus.sessionPaused
                                ? '恢复Session'
                                : '暂停Session',
                            style: const TextStyle(fontSize: 10),
                            textAlign: TextAlign.center,
                            maxLines: 2,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 显示实现方案选择对话框
  void _showImplementationDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择摄像头实现方案'),
        contentPadding: const EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 24.0),
        content: SizedBox(
          width: MediaQuery.of(context).size.width * 0.8, // 限制宽度
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              // 平台提示信息
              Container(
                padding: const EdgeInsets.all(8),
                margin: const EdgeInsets.only(bottom: 16),
                decoration: BoxDecoration(
                  color: Colors.blue[50],
                  border: Border.all(color: Colors.blue[200]!),
                  borderRadius: BorderRadius.circular(4),
                ),
                child: const Text(
                  '提示：Flutter Camera 主要支持 iOS 和 Android 平台。在 macOS 上建议使用原生实现。',
                  style: TextStyle(fontSize: 12, color: Colors.blue),
                ),
              ),
              // 实现方案列表
              ..._availableImplementations.map((impl) {
                final isSelected = impl == _currentImplementation;
                final isRecommendedForPlatform = (Platform.isMacOS &&
                        impl == CameraImplementationType.native) ||
                    (!Platform.isMacOS &&
                        impl != CameraImplementationType.native);

                return Container(
                  margin: const EdgeInsets.symmetric(vertical: 4),
                  child: InkWell(
                    onTap: () {
                      Navigator.of(context).pop();
                      _switchImplementation(impl);
                    },
                    borderRadius: BorderRadius.circular(8),
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 16, vertical: 12),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: isSelected ? Colors.blue : Colors.grey[300]!,
                          width: isSelected ? 2 : 1,
                        ),
                        borderRadius: BorderRadius.circular(8),
                        color: isSelected ? Colors.blue[50] : null,
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          // 左侧：单选按钮和实现方案名称
                          Expanded(
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Radio<CameraImplementationType>(
                                  value: impl,
                                  groupValue: _currentImplementation,
                                  onChanged: (value) {
                                    Navigator.of(context).pop();
                                    if (value != null) {
                                      _switchImplementation(value);
                                    }
                                  },
                                  materialTapTargetSize:
                                      MaterialTapTargetSize.shrinkWrap,
                                ),
                                const SizedBox(width: 8),
                                Flexible(
                                  child: Text(
                                    _getImplementationName(impl),
                                    style: TextStyle(
                                      fontWeight: isSelected
                                          ? FontWeight.bold
                                          : FontWeight.normal,
                                    ),
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          // 右侧：标签和选中图标
                          Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              if (isRecommendedForPlatform) ...[
                                Container(
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 6, vertical: 2),
                                  decoration: BoxDecoration(
                                    color: Colors.green[100],
                                    borderRadius: BorderRadius.circular(10),
                                  ),
                                  child: const Text(
                                    '推荐',
                                    style: TextStyle(
                                        fontSize: 10, color: Colors.green),
                                  ),
                                ),
                                const SizedBox(width: 8),
                              ],
                              if (isSelected)
                                const Icon(Icons.check,
                                    color: Colors.green, size: 20),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              }).toList(),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }
}
